#include <thirdparty/fist-log.h>

#include <filesystem>

#include "fist-config.h"

IFistConfig::IFistConfig()
    : m_next_check(0)
    , m_last_modify(0)
{
    
}

IFistConfig::~IFistConfig()
{
    
}

bool IFistConfig::Load(const char* filepath)
{
    m_filepath = filepath;
    m_next_check = fist::get_now_ms_time() + FILE_CHECK_TIME;
    return Read(m_filepath);
}

bool IFistConfig::Update()
{
    if (fist::get_now_ms_time() < m_next_check) {
        return true;
    }
    m_next_check = fist::get_now_ms_time() + FILE_CHECK_TIME;
    if (!CheckFileChange()) {
        return true;
    }
    m_last_modify = fist::get_now_ms_time();
    return Read(m_filepath);
}

bool IFistConfig::CheckFileChange()
{
    if (!std::filesystem::exists(m_filepath)) {
        LOG_FATAL("config not exists, path:{}", m_filepath);
        return false;
    }

    return std::chrono::duration_cast<std::chrono::milliseconds>(
        std::filesystem::last_write_time(m_filepath).time_since_epoch()).count() != m_last_modify;
}
